package com.giornoadd.timex.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.hibernate.HibernateException;

import com.giornoadd.timex.model.Employee;
import com.giornoadd.timex.util.HibernateUtil;

/**
 * Manages database operations for Employee table.
 * @author anil
 */
public class EmployeeManager
{
    /**
     * Returns list of all Employee records matching employeeCode 'H'
     */
    @SuppressWarnings("unchecked")
	public List<Employee> getHourlyEmployees()
    {
        List<Employee> employeeList = null;

        EntityManager entityManager = HibernateUtil.getEntityManager();
        
        try
        {
        	entityManager.getTransaction().begin();
            employeeList = entityManager.createQuery(
                    "from Employee WHERE employeeCode='H'"
                            + "ORDER BY name").getResultList();
            entityManager.getTransaction().commit();
        }
        catch (HibernateException e)
        {
        	entityManager.getTransaction().rollback();
            throw e;
        }

        return employeeList;
    }

    /**
     * Gets employee record with matching employeeId
     */
    public Employee getEmployee(int employeeId)
    {
        Employee employee = null;

        EntityManager entityManager = HibernateUtil.getEntityManager();
        
        try
        {
        	entityManager.getTransaction().begin();
            employee = (Employee) entityManager.createQuery(
                    "from Employee WHERE employeeId = ?1").setParameter(1,
                    employeeId).getSingleResult();
            entityManager.getTransaction().commit();
        }
        catch (HibernateException e)
        {
        	entityManager.getTransaction().rollback();
            throw e;
        }

        return employee;
    }
}
